using Microsoft.EntityFrameworkCore;
using MudWebApp.Data;
using MudWebApp.Helps;
using MudWebApp.Models;
using MudWebApp.Repositories.Contracts;
using MudWebApp.Requests;
using MudWebApp.Responses;

namespace MudWebApp.Repositories.Implementations;

public class Account(AppDbContext appDbContext, IConfiguration configuration) : IAccount
{
    public async Task<RegisterResult> RegisterAsync(RegisterData data)
    {
        var user = await appDbContext.AppUsers.FirstOrDefaultAsync(x => x.Email == data.Email);
        if (user is null)
        {
            var newUser = new AppUser
            {
                Id = Guid.NewGuid(),
                Name = data.Name,
                Email = data.Email,
                Password = BCrypt.Net.BCrypt.HashPassword(data.Password)
            };
            await appDbContext.AppUsers.AddAsync(newUser);
        }
        else
        {
            return new RegisterResult(false, "User is Existed");
        }

        await appDbContext.SaveChangesAsync();
        return new RegisterResult(true, "Register Success");
    }

    public async Task<LoginResult> LoginAsync(LoginData data)
    {
        var user = await appDbContext.AppUsers.FirstOrDefaultAsync(x => x.Email == data.Email);
        if (user is null)
            return new LoginResult(false, "User is not Existed");
        if (!BCrypt.Net.BCrypt.Verify(data.Password, user.Password))
            return new LoginResult(false, "Password is Incorrect");
        return new LoginResult(true, "Login Success",
            new JwtHelper(configuration).GenerateAccessToken(user, "system"),
            JwtHelper.GenerateRefreshToken());
    }
}